<template>
  <div class="mainWrapper">
    <div class="searchBox">
      所属类别：
      <el-radio-group v-model="displayCategory" class="radioGroup" @change="handleChange">
        <el-radio-button label="all">全部</el-radio-button>
        <el-radio-button v-for="item in categoryList" :key="item" :label="item">
          {{ item }}
        </el-radio-button>
      </el-radio-group>
    </div>
    <div v-loading="loading" class="resultArea">
      <el-card v-for="item in chipData.data" :key="item.chipId" class="box-card">
        <div slot="header" class="clearfix">
          <el-tooltip
            :disabled="getStrLength(item.displayName) < 20"
            effect="dark"
            :content="item.displayName"
            placement="top"
          >
            <span class="title ellipsis">
              {{ item.displayName }}
            </span>
          </el-tooltip>
          <div>
            <el-link
              v-permission="['chipLibraryManagement:chipLibrary:view']"
              type="primary"
              :underline="false"
              @click="handleClick('view', item)"
            >
              查看
            </el-link>
            <el-link
              v-if="item.type === 2"
              v-permission="['chipLibraryManagement:chipLibrary:edit']"
              type="primary"
              :underline="false"
              @click="handleClick('edit', item)"
            >
              编辑
            </el-link>
            <el-dropdown
              v-else
              v-permission="['chipLibraryManagement:chipLibrary:edit']"
              @command="handleClick($event, item)"
            >
              <el-link type="primary" :underline="false">
                编辑
                <i class="el-icon-arrow-down"></i>
              </el-link>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="edit">编辑芯片信息</el-dropdown-item>
                <el-dropdown-item command="updateChipFile">修改芯片文件</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-popconfirm
              v-permission="['chipLibraryManagement:chipLibrary:del']"
              title="确定删除吗？"
              @confirm="handleClick('del', item)"
            >
              <el-link slot="reference" type="primary" :underline="false">删除</el-link>
            </el-popconfirm>
          </div>
        </div>
        <el-tooltip :disabled="getStrLength(item.model) < 30" effect="dark" :content="item.model" placement="top">
          <div class="text ellipsis">芯片型号：{{ item.model }}</div>
        </el-tooltip>
        <el-tooltip
          :disabled="getStrLength(item.displayCategory) < 30"
          effect="dark"
          :content="item.displayCategory"
          placement="top"
        >
          <div class="text ellipsis">芯片类别：{{ item.displayCategory }}</div>
        </el-tooltip>
        <el-tooltip
          :disabled="getStrLength(item.manufacturer) < 30"
          effect="dark"
          :content="item.manufacturer"
          placement="top"
        >
          <div class="text ellipsis">芯片厂家：{{ item.manufacturer }}</div>
        </el-tooltip>
        <el-tooltip
          :disabled="getStrLength(item.description) < 34"
          effect="dark"
          :content="item.description"
          placement="top"
        >
          <div class="text ellipsis">描述：{{ item.description }}</div>
        </el-tooltip>
      </el-card>
      <el-empty
        v-if="chipData.data.length === 0 && !loading"
        class="emptyBox"
        :image="require('@/assets/imgs/empty.png')"
      ></el-empty>
      <chipDetail ref="chipDetail" :category-list="categoryList" @refresh="handleRefreshParent" />
      <!-- <updateChip ref="updateChip" @refresh="handleRefreshParent" /> -->
    </div>
    <pagination
      class="myPagination"
      :table-total-size="chipData.tableTotalSize"
      :search-data="searchData"
      @getTableData="handleSearch"
    />
  </div>
</template>

<script>
import pagination from '@/components/Table/pagination'
import { getStrLength } from '@/utils/index'
import chipDetail from './chipDetail.vue'
// import updateChip from './updateChip.vue'
import { getChipData, deleteChip, getChipDetail } from '@/api/project-management'
import defaultSettings from '@/settings'
import { generateUUID, postMessage, receivedMessage } from '@/utils/index'
export default {
  components: { pagination, chipDetail },
  props: {
    chipType: {
      type: Number,
      default: 1
    },
    categoryList: {
      type: Array,
      default: () => {
        return []
      }
    },
    fixedChipCategory: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      loading: false,
      displayCategory: 'all',
      searchData: {
        pageSize: 15,
        currentPage: 1,
        sort: {},
        params: {
          displayCategory: undefined
        }
      },
      chipData: {
        data: [],
        tableTotalSize: 0
      },
      getChipDataRequestId: generateUUID(),
      deleteChipRequestId: generateUUID(),
      getChipDetailRequestId: generateUUID(),
      currentRow: {}
    }
  },
  created() {
    this.searchData.params.type = this.chipType
  },
  mounted() {
    receivedMessage(this.dataHandle)
  },
  methods: {
    dataHandle(result) {
      let self = this
      let e = defaultSettings.isWPF ? result : { data: JSON.parse(result) }
      if (e.data.webInfo.requestId === self.getChipDataRequestId) {
        self.chipData = {
          data: e.data.response.data.data,
          tableTotalSize: e.data.response.data.total_count
        }
        self.loading = false
      } else if (e.data.webInfo.requestId === self.deleteChipRequestId) {
        if (e.data.response.success) {
          self.handleRefreshParent(self.currentRow.type)
          self.$message.success('删除成功')
        } else {
          self.$message.error(e.data.response.message)
        }
      } else if (e.data.webInfo.requestId === self.getChipDetailRequestId) {
        self.openChipDetail(e.data.response)
      }
    },
    getStrLength(str) {
      return getStrLength(str)
    },
    handleRefreshParent(chipType) {
      if (!this.fixedChipCategory.includes(this.displayCategory)) {
        this.displayCategory = 'all'
        this.searchData.params.displayCategory = undefined
        this.searchData.currentPage = 1
      }
      this.$emit('refresh', chipType)
    },
    refreshData(name) {
      this.searchData.params.displayName = name
      this.searchData.params.model = name
      this.handleChange()
    },
    handleChange(val) {
      this.searchData.params.displayCategory = val === 'all' ? undefined : this.displayCategory
      this.searchData.currentPage = 1
      this.handleSearch()
    },
    handleSearch() {
      if (this.searchData.params.displayCategory === 'all') {
        this.searchData.params.displayCategory = undefined
      }
      this.loading = true
      if (defaultSettings.isWPF || defaultSettings.isCEF) {
        this.getChipDataRequestId = generateUUID()
        let message = {
          RequestUrl: process.env.VUE_APP_URL + '/chip/loadGrid',
          RequestMethod: 'POST',
          Headers: {
            contentType: 'application/json'
          },
          QueryParameter: {},
          RequestBody: this.searchData,
          WebInfo: {
            requestId: this.getChipDataRequestId
          }
        }
        postMessage(message)
      } else {
        getChipData(this.searchData).then((res) => {
          this.chipData = {
            data: res.data.data,
            tableTotalSize: res.data.total_count
          }
          this.loading = false
        })
      }
    },
    handleClick(name, row) {
      if (name === 'del') {
        this.currentRow = row
        if (defaultSettings.isWPF || defaultSettings.isCEF) {
          this.deleteChipRequestId = generateUUID()
          let message = {
            RequestUrl: process.env.VUE_APP_URL + '/chip/delete',
            RequestMethod: 'POST',
            Headers: {
              contentType: 'application/json'
            },
            QueryParameter: {},
            RequestBody: { chipId: row.chipId },
            WebInfo: {
              requestId: this.deleteChipRequestId
            }
          }
          postMessage(message)
        } else {
          deleteChip({ chipId: row.chipId }).then((res) => {
            if (res.success) {
              this.handleRefreshParent(row.type)
              this.$message.success('删除成功')
            } else {
              this.$message.error(res.message)
            }
          })
        }
      } else {
        this.currentRow = row
        this.drawerType = name
        if (defaultSettings.isWPF || defaultSettings.isCEF) {
          this.getChipDetailRequestId = generateUUID()
          let message = {
            RequestUrl: process.env.VUE_APP_URL + '/chip/getChipInfo',
            RequestMethod: 'POST',
            Headers: {
              contentType: 'application/json'
            },
            QueryParameter: {},
            RequestBody: { chipId: row.chipId },
            WebInfo: {
              requestId: this.getChipDetailRequestId
            }
          }
          postMessage(message)
        } else {
          getChipDetail({ chipId: row.chipId }).then((res) => {
            this.openChipDetail(res)
          })
        }
      }
    },
    openChipDetail(res) {
      if (res.success) {
        if (this.drawerType === 'updateChipFile') {
          this.$emit('handleClick', 'updateChip', {
            ...this.currentRow,
            chipDefinitionFiles: res.data.chipDefinitionFiles
          })
        } else {
          let data = {
            ...this.currentRow,
            chipDefinitionFiles: res.data.chipDefinitionFiles,
            pinFiles: res.data.pinFiles,
            pinFilesBase64: res.data.pinFilesBase64,
            circuitGenerationModuleChipList: res.data.circuitGenerationModuleChipList
          }
          if (data.type === 1) {
            data.clockParameters = res.data.clockParameters
            data.clockParameterFiles = res.data.clockParameterFiles
            data.clockParameterFilesBase64 = res.data.clockParameterFilesBase64
            data.circuitGenerationModuleChipList = res.data.circuitGenerationModuleChipList
          } else {
            data.performanceParameterFiles = res.data.performanceParameterFiles
            data.performanceParameterFilesBase64 = res.data.performanceParameterFilesBase64
          }
          this.$refs.chipDetail.is(this.drawerType, data)
        }
      } else {
        this.$message.error(res.message)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/element-variables.scss';
.mainWrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
  .searchBox {
    display: flex;
    line-height: 32px;
    .radioGroup {
      flex: 1;
      /deep/.el-radio-button {
        margin-right: 10px;
        margin-bottom: 10px;
        .el-radio-button__inner {
          border-left: 1px solid #dcdfe6;
          border-radius: 4px;
        }
        .el-radio-button__orig-radio:checked + .el-radio-button__inner {
          border-color: $--color-primary;
        }
      }
    }
  }
  .resultArea {
    flex: 1;
    overflow-y: auto;
    display: flex;
    flex-wrap: wrap;
    align-content: baseline;
    .box-card {
      width: 321px;
      margin-right: 10px;
      margin-bottom: 10px;
      align-self: baseline;
      .text {
        margin-bottom: 10px;
      }
      .clearfix {
        display: flex;
        align-items: center;
        justify-content: space-between;
        .title {
          font-weight: 600;
          flex: 1;
        }
        .el-link + .el-link {
          margin-left: 0;
        }
      }
    }
    .el-empty {
      width: 100%;
    }
  }
  .myPagination {
    margin-top: 10px;
    /deep/.page {
      position: unset;
      margin-bottom: 0;
    }
  }
}
</style>
